﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using SybaseLogRecovery.Properties;

namespace SybaseLogRecovery
{
    public partial class Form1 : Form
    {
        private readonly LogParser _parser;
        private OdbcConnectionStringBuilder _builder;
        public Dictionary<string, string> SybaseConnections { get; set; }
        public Form1()
        {
            InitializeComponent();
            _parser = new LogParser(checkBox2.Checked, checkBox1.Checked);
            _builder = new OdbcConnectionStringBuilder(Settings.Default.dataConnectionString);

            SybaseConnections = DataBaseStatics.GetSybaseConnectionNames();
            comboBox1.DataSource = SybaseConnections != null ? new List<string>(SybaseConnections.Keys) : new List<string>() { "Пользовательская настройка" };
            comboBox1.SelectedItem = GetServerAliasFromCurrentBuilder();

            if (!DataBaseStatics.ConnectionCheck())
            {
                new DataBaseConnection().ShowDialog();
            }
            button3_Click(null, null);
        }

        private string GetServerAliasFromCurrentBuilder()
        {
            if (_builder.ContainsKey("Server") && SybaseConnections != null)
            {
                var alias = SybaseConnections.FirstOrDefault(x => x.Value == (string)_builder["Server"]);
                return alias.Key;
            }
            else
            {
                return "Пользовательская настройка";
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            _parser.StartParse(textBox1.Text, textBox4.Text);

            linkLabel1.Text = _parser.DbProcName;
            //label3.Text = "параметров: " + _parser.DbParamCount;
            label4.Text = "найдено параметров: " + _parser.ParsedParams.Count + "/" + _parser.DbParamCount;
            linkLabel4.Text = _parser.AbsentParams.Count.ToString();
            linkLabel3.Text = _parser.ErrorParams.Count.ToString();
            textBox2.Text = _parser.ResultSql;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_parser != null)
            {
                new ParamsViewer(ToTable(_parser.ParsedParams)).Show();
            }
        }

        /// <summary>
        /// Кнопка TEST
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            var connected = DataBaseStatics.ConnectionCheck(_builder.ToString());

            if (!connected)
            {
                label1.Text = "отсутствует подключение к базе";
                label1.ForeColor = Color.Coral;
            }
            else
            {
                label1.Text = "установлено соединение с " + _builder["DataBase"];
                label1.ForeColor = Color.LightSeaGreen;

            }

            if (sender != null)
            {
                var stateMessage = (connected == false) ? "Отсутствует подключение к базе!" : "Подключение успешно установлено!";
                var stateIcon = (connected == false) ? MessageBoxIcon.Error : MessageBoxIcon.Asterisk;
                MessageBox.Show(stateMessage, "Проверка подключения", MessageBoxButtons.OK, stateIcon);

            }
        }


        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_parser != null)
            {
                new ParamsViewer(_parser.DT).Show();
            }
        }

        private static DataTable ToTable(Dictionary<string, string> list)
        {
            DataTable result = new DataTable();
            if (list == null || list.Count == 0)
                return result;


            result.Columns.Add(new DataColumn() { DataType = Type.GetType("System.String"), ColumnName = "key" });
            result.Columns.Add(new DataColumn() { DataType = Type.GetType("System.String"), ColumnName = "value" });

            foreach (var listItem in list)
            {

                DataRow workRow = result.NewRow();
                workRow["key"] = listItem.Key;
                workRow["value"] = listItem.Value;
                result.Rows.Add(workRow);
            }
            return result;
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_parser != null)
            {
                new ParamsViewer(ToTable(_parser.AbsentParams)).Show();
            }

        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_parser != null)
            {
                new ParamsViewer(ToTable(_parser.ErrorParams)).Show();
            }

        }

        /// <summary>
        /// Открытие окна настройки соединения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            new DataBaseConnection().ShowDialog();
            _builder = new OdbcConnectionStringBuilder(Settings.Default.dataConnectionString);
            comboBox1.SelectedItem = GetServerAliasFromCurrentBuilder();
            button3_Click(null, null);
        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            var s = sender as ComboBox;
            if (s != null && SybaseConnections != null)
            {
                if (SybaseConnections.ContainsKey(s.SelectedItem.ToString()))
                {
                    _builder["Server"] = SybaseConnections[s.SelectedItem.ToString()];
                }
                button3_Click(null, null);
            }
        }

        private void textBox1_PastedText(object sender, ClipboardTextBoxExample.ClipboardEventArgs e)
        {
            textBox1.Text = e.ClipboardText;
            button1_Click(null, null);
            textBox1.Text = String.Empty;
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                if (sender != null)
                    ((TextBox)sender).SelectAll();
            }
        }

        private void checkBox1_CheckStateChanged(object sender, EventArgs e)
        {
            _parser.OutDeclare = checkBox1.Checked;
        }

        private void checkBox2_CheckStateChanged(object sender, EventArgs e)
        {
            _parser.SkipAt = checkBox2.Checked;
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Clipboard.SetDataObject(textBox2.Text);
        }

        private void button2_Click(object sender, LinkLabelLinkClickedEventArgs e)
        {
            textBox1.Text = String.Empty;
            textBox2.Text = String.Empty;
            linkLabel1.Text = "нет";
            label4.Text = "найдено параметров:";
            linkLabel3.Text = "0";
            linkLabel4.Text = "0";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.paypal.me/trinitron/10");
        }
    }
}
